package com.gupao.delegatedemo.servletdemo.controller;

import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ServletDispatch {

    private List<Hander> handerMapping = new ArrayList<>();

    public ServletDispatch(){

        //模拟handerMapping 已将全部controller的Action加入handerMapping
        Class<?> clazz = SystemController.class;
        try {
            Hander hander = new Hander();
            hander.setController(clazz.newInstance());
            hander.setMethod(clazz.getMethod("getSystemById",new Class[]{Integer.class}));
            hander.setUrl("/web/system/getsysteminfo");
            this.handerMapping.add(hander);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doservice(HttpServletRequest request, HttpServletResponse response){
        doDispatch(request,response);
    }

    private void doDispatch(HttpServletRequest request, HttpServletResponse response){
        //1获取用户请求的url地址
        String uri = request.getRequestURI();
        //2servlet拿到url地址要去做权衡（做判断和选择）
        //3通过拿到的url去和handerMapping里面的做比较,此处应该引入策略模式
        Hander hander = null;
        for (Hander h: handerMapping) {
            if(h.getUrl().equals(uri)){
                hander=h;
                break;
            }
        }
        //将具体的任务发给Method(利用反射区执行方法)
        Object controller = hander.getController();
        Method method = hander.getMethod();
        Object result = null;
        try {
            result = method.invoke(controller,request.getParameter("id"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

//            response.getWriter().write();


    }


    @Data
    class Hander{
        private Object controller;
        private Method method;
        private String url;

    }
}
